package com.belf.evaluatetool.service.impl;

import belf.migrate.api.taskconf.SourceConf;
import belf.migrate.engine.job.Result;
import com.belf.evaluatetool.common.SysConfig;
import com.belf.evaluatetool.service.DatabaseService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * DatabaseServiceImpl
 *
 * @author l
 * @since 2024/10/28 16:58
 */

@Log4j2
@Service
public class DatabaseServiceImpl implements DatabaseService {

    @Override
    public Result checkDatabase(SourceConf sourceConf) {
        Connection connection = null;
        buildUrl(sourceConf);
        try {
            log.info("连接数据库: {}", sourceConf.toString());
            connection = DriverManager.getConnection(sourceConf.getConnectionConf().getUrl(), sourceConf.getConnectionConf().getUser(), sourceConf.getConnectionConf().getPassword());
            if (connection.isValid(5)) {
                return Result.success();
            } else {
                return Result.sqlFail("连接失效");
            }
        } catch (SQLException e) {
            log.error("连接失败", e);
            return Result.sqlFail(e.getMessage());
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    log.error("连接关闭失败");
                }
            }

        }
    }

    public void   buildUrl(SourceConf sourceConf) {
        String url="";
        SysConfig sysConfig = new SysConfig();
        switch (sourceConf.getCatalogName().toLowerCase()) {
            case "mysql":
                url = String.format("jdbc:mysql://%s:%s/%s?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false",
                        sourceConf.getConnectionConf().getHost(),
                        sourceConf.getConnectionConf().getPort(),
                        sourceConf.getDatabaseName());
                sourceConf.getConnectionConf().setDriver(sysConfig.getMysqlDriver());
                break;
            case "oracle":
                url = String.format("jdbc:oracle:thin:@%s:%s/%s",
                        sourceConf.getConnectionConf().getHost(),
                        sourceConf.getConnectionConf().getPort(),
                        sourceConf.getSchemaName());
                sourceConf.getConnectionConf().setDriver(sysConfig.getOracleDriver());
                break;
        }
        sourceConf.getConnectionConf().setUrl(url);
    }
}
